import 'dart:convert';
import 'dart:io';

import 'package:photo_manager/photo_manager.dart';

import '/app/utils/file_size_converter.dart';
import '/app/utils/time_utils.dart';

class VideoInfoEntity {
  // 视频文件的唯一ID
  final String assetId;
  // 文件名称
  String title;
  // 文件路径
  String path;
  // 文件大小 字节
  int size;
  // 视频时长 (ms)
  int duration;
  // 构造函数
  VideoInfoEntity({
    required this.assetId,
    required this.title,
    required this.path,
    required this.size,
    required this.duration,
  });

  // 从JSON字符串转换
  factory VideoInfoEntity.fromJsonString(String jsonString) {
    final Map<String, dynamic> json = jsonDecode(jsonString);
    return VideoInfoEntity(
      assetId: json['assetId'],
      title: json['title'],
      path: json['path'],
      size: json['size'],
      duration: json['duration'],
    );
  }

  // 转换为JSON字符串
  String toJsonString() {
    return jsonEncode({
      'assetId': assetId,
      'title': title,
      'path': path,
      'size': size,
      'duration': duration,
    });
  }

  // 获取视频时长字符串
  String getDurationStr() {
    if (duration <= 0) return "";
    return TimeUtils.millisecondsToFormattedTime(duration);
  }

  // 获取文件大小字符串
  String getSizeStr() {
    return FileSizeConverter.convertToReadableSize(size);
  }

  // 将 `AssetEntity` 转换为 `VideoInfoEntity`
  static Future<VideoInfoEntity> convert(AssetEntity assetEntity) async {
    File? file = await assetEntity.originFile;
    int size = file != null ? await file.length() : 0;
    String path = assetEntity.relativePath ?? "";
    String assetId = assetEntity.id;
    String title = assetEntity.title ?? "";
    int duration = assetEntity.duration;

    // 创建 VideoInfoEntity 对象
    VideoInfoEntity videoInfo = VideoInfoEntity(
      assetId: assetId,
      title: title,
      path: path,
      size: size,
      duration: duration * 1000, // 以毫秒为单位
    );

    return videoInfo;
  }
}
